package api;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import util.DBUtils;
import util.ResultUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 用户登录
 */
@WebServlet("/reg")
public class RegServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        int data=0;//返回的结果标识，1=注册过成功，！=1=注册失败
        String msg="未知错误";
        //1.得到参数从前端
        String username=req.getParameter("username");
        String nickname=req.getParameter("nickname");
        String password=req.getParameter("password");

        //1.1非空校验
        if(!StrUtil.isBlank(username)&&!StrUtil.isBlank(password )&&!StrUtil.isBlank(nickname)){
            //2.将数据保存到数据库
            //2.1得到连接
            Connection connection=DBUtils.getConnection();
            //2.2先判断
            String selSql="select * from userinfo where username=?";
           PreparedStatement statement=connection.prepareStatement(selSql);
           statement.setString(1,username);
            ResultSet resultSet= statement.executeQuery();
           if(resultSet.next()){
               msg="您输入的用户名已存在，请重新输入";
           }else{
               //2.2拼接SQL语句
               String sql="insert into userinfo(username,nickname,password) values(?,?,?)";
              statement= connection.prepareStatement(sql);

               //2.3给执行器填充属性并执行
               statement.setString(1,username);
               statement.setString(2,nickname);
               statement.setString(3, SecureUtil.md5(password));
               data=statement.executeUpdate();
               //关闭资源
           }
           DBUtils.close(null,statement,connection);
        }else{
        msg="非法访问！";
        }
        //3.将数据库返回的结果返回到前端
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtil.toResult(200,data,msg)));
    }
}
